/**
 * @Description: 规则配置
 * @author dazer
 * @date 2019/2/1 下午12:09
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Form,
  Icon,
  Input,
  Radio,
  Select,
  Upload,
  BackTop,
  Tooltip,
  Divider,
} from 'antd';
import Modal from 'drag-modal';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import jsonp from 'fetch-jsonp';
import querystring from 'querystring';
import Zmage from 'react-zmage';
import { connect } from 'dva';
import { reqeustRemoteValidate, requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '@/components/ourslook/BaseForm';
import ETable from '@/components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const getSysConfigTypeMap = {
  '1': '字符型',
  '2': '数字型',
  '3': '时间型',
  '4': 'Boolean型',
  // '5': '数组型',//数组类型，暂不支持
  //'6': '文件型', //文件类型有问题，赞不支持
  '7': '图片型',
};

@connect(() => ({}))
class SysConfigMgr extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（建议留一列不设宽度以适应弹性布局）, 一般无table正常展开的宽度
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => `${index + 1}`,
    },
    {
      title: '参数名',
      dataIndex: 'keyAlias',
      width: 200,
      align: 'left',
      fixed: 'left',
      sorter: true,
    },
    {
      title: '参数值',
      dataIndex: 'value',
      width: 120,
      align: 'left',
      render: (value, record) => {
        if (record.type === '6' || record.type === '7') {
          if (record.type === '6') {
            return <a onClick={() => this.handleAttachModalVisible(record)}>附件</a>;
          }
          return <a onClick={() => this.handleAttachModalVisible(record)}>图片</a>;
        }
        return record.value;
      },
    },
    { title: '参数编码', dataIndex: 'code', align: 'left' },
    { title: '创建时间', dataIndex: 'createTime', width: 180, align: 'center' },
    {
      title: '参数类型',
      dataIndex: 'type',
      width: 80,
      fixed: 'right',
      render(value) {
        let desc = getSysConfigTypeMap[value];
        if (desc === undefined) {
          desc = '';
        }
        return desc;
      },
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: '',
      width: 120,
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
            hidden={!hasPermission('sys:config:info')}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>

          <Divider hidden={!hasPermission('sys:config:info')} type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
            hidden={!hasPermission('sys:config:update')}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.update" defaultMessage="修改" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>

          <Divider hidden={!hasPermission('sys:config:update')} type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.copy();
            }}
            hidden={!hasPermission('sys:config:update')}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />}>
              <Icon type="copy" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      formList: SysConfigMgr.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      galleryModelVisible: false,
      galleryCurrentRecord: false,
      editModalTitle: null,
      editModalIsVisible: false,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
    };
  }

  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'key',
      label: '参数名',
      placeholder: '参数名',
    },
    {
      type: 'INPUT',
      field: 'code',
      label: '参数编码',
      placeholder: '参数编码',
    },
    {
      type: 'SELECT',
      field: 'type',
      placeholder: '参数类型',
      initialValue: '',
      list: [
        { id: '', name: '请选择参数类型' },
        ...uiUtils.getOptionJsonObjToArr(getSysConfigTypeMap),
      ],
    },
    {
      type: 'DATE_RANGE',
      field: 'createTime',
      label: '请选择创建日期',
      placeholder: ['创建日期', ''],
    },
    {
      type: 'DATE',
      field: 'updateTime',
      label: '更新日期',
      placeholder: '更新日期',
      format: 'YYYY-MM-DD',
      showTime: false,
    },
    {
      type: 'SELECT_REMOTE',
      label: '随机搜索',
      field: 'taobaoShopSelectRemote',
      placeholder: '键入字符进行搜索',
      initialValue: '1',
      list: [],
      handleRemoteSearch: null,
    },
  ];

  componentDidMount() {
    this.requestList();

    //模拟动态修改表单，不要删除
    // this.timeout = setTimeout(() => {
    //   const {formList: formListNew} = this.state;
    //   const formItem = this.findFormListItemByField('type');//type 是 field的取值
    //   formItem.list = [{id: '10', name: '全部1'}, {id: '11', name: '进行中'}, {id: '12', name: '结束行程2'}, {id: '13', name: '结束行程2'}, {id: '14', name: '结束行程2'}, {id: '15', name: '结束行程2'}, {id: '16', name: '结束行程2'}];
    //   this.setState({
    //     formList: formListNew,
    //   });
    // }, 5000);

    const { formList } = this.state;
    const formItem = this.findFormListItemByField('taobaoShopSelectRemote');
    formItem.handleRemoteSearch = this.handleRemoteSearch;
    this.setState({ formList });
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalIsVisible: true,
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: { type: '1' },
    });
  };

  update = () => {
    const { selectedIndexs, selectedRows, selectedIds } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalIsVisible: true,
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: selectedRows[0],
    });
  };

  copy = () => {
    const { selectedIndexs, selectedRows, selectedIds } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }

    const sysConfig = selectedRows[0];
    sysConfig.id = null;

    this.setState({
      editModalType: 'copy',
      editModalIsVisible: true,
      editModalTitle: <FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />,
      editModel: sysConfig,
    });
  };

  view = () => {
    const { selectedIndexs, selectedRows, selectedIds } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalIsVisible: true,
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
    });
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      if (selectedRows[i].code === 'CONFIG_SYS_LOGO') {
        uiUtils.showAlert('系统logo不能删除');
        return;
      }
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/config/delete')}`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const config = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = config.id == null ? 'sys/config/save' : 'sys/config/update';

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: config,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });

          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              editModalIsVisible: false,
            });
            this.editForm.props.form.resetFields();

            if (config.code === 'CONFIG_SYS_LOGO') {
              //window.parent.location.reload();
              this.sysLogoChange(config);
            } else {
              //新增重新置为第一页
              if (!config.id) {
                this.params.page = 1;
              }
              this.requestList();
            }
          }
        });
      }
    });
  };

  handleRemoteSearch = value => {
    const str = querystring.encode({
      code: 'utf-8',
      q: value,
    });
    jsonp(`https://suggest.taobao.com/sug?${str}`)
      .then(response => response.json())
      .then(d => {
        const result = d.result;
        const data = [];
        result.forEach(r => {
          data.push({
            id: `${r[0]}id`,
            name: r[0],
          });
        });

        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('taobaoShopSelectRemote');
        formItem.list = data;
        this.setState({
          formList: formListNew,
        });
      });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('sys/config/list')}`, this.params);
  };

  /**
   * 处理表格点击附件的事件
   * @param record
   */
  handleAttachModalVisible = record => {
    this.setState({
      galleryModelVisible: true,
      galleryCurrentRecord: record,
    });
  };

  downloadFile = url => {
    //window.location = url;
    window.open(`${url}`, '_blank');
  };

  /**
   * 处理
   */
  sysLogoChange = sysConfigModel => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ourslook/fetchLogoConfigFromUpdate',
      payload: {
        logoOnline: sysConfigModel.value,
      },
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    let footer = {};
    if (this.state.editModalType === 'view') {
      footer = {
        footer: null,
      };
    }

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card bordered={false} className={styles.oursCard} bodyStyle={{ padding: '20px' }}>
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('sys:config:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="primary"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('sys:config:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="keyAlias"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1200 }}
            />
          </div>
        </Card>

        <BackTop />

        {/*查看图片或者附件的对话框*/}
        <Modal
          width={300}
          height={500}
          visible={this.state.galleryModelVisible}
          title={this.state.galleryCurrentRecord.type === '6' ? '附件' : '图片'}
          onCancel={() => {
            this.setState({
              galleryModelVisible: false,
            });
          }}
          saveDistance={0}
          footer={null}
        >
          {this.state.galleryCurrentRecord.type === '7' && (
            <Zmage
              src={this.state.galleryCurrentRecord.value}
              alt=""
              style={{ width: '100%', cursor: 'pointer' }}
            />
          )}
          {this.state.galleryCurrentRecord.type === '6' && (
            <Button
              size="small"
              icon="download"
              onClick={() => {
                this.downloadFile(this.state.galleryCurrentRecord.value);
              }}
            >
              下载
            </Button>
          )}
        </Modal>

        {/*新增、编辑、复制、查看的编辑框*/}
        <Modal
          title={this.state.editModalTitle}
          visible={this.state.editModalIsVisible}
          onOk={this.saveOrUpdate}
          onCancel={() => {
            this.editForm.props.form.resetFields();
            this.setState({
              editModalIsVisible: false,
            });
          }}
          destroyOnClose
          confirmLoading={this.state.editModelConfirmLoading}
          okButtonProps={{ icon: 'down-circle' }}
          width={600}
          saveDistance={0}
          {...footer}
        >
          <EditForm
            type={this.state.editModalType}
            model={this.state.editModel}
            loadingCallback={loading => {
              if (this.state.editModelConfirmLoading !== loading) {
                this.setState({
                  editModelConfirmLoading: loading,
                });
              }
            }}
            wrappedComponentRef={inst => {
              this.editForm = inst;
            }}
          />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default SysConfigMgr;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    loadingCallback: PropTypes.func, //子容器loading情况，反馈callback给父
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    loadingCallback: () => {},
  };

  constructor(props) {
    super(props);
    const configType = this.props.model && this.props.model.type ? this.props.model.type : '1'; //默认是，字符型
    const defaultFileList =
      this.props.model &&
      (this.props.model.type === '7' || this.props.model.type === '6') &&
      this.props.model.value
        ? [
            {
              uid: '1',
              name: '',
              status: 'done',
              url: this.props.model.value,
            },
          ]
        : null; //defaultFileList
    this.state = {
      configType,
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultFileList, //上传文件列表
      fileList: defaultFileList && defaultFileList.length > 0 ? [defaultFileList[0]] : [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  handleUploadPreview = file => {
    const previewImage = file.url || file.thumbUrl;
    const previewVisible =
      previewImage.toLowerCase().endsWith('.bpm') ||
      previewImage.toLowerCase().endsWith('.png') ||
      previewImage.toLowerCase().endsWith('.jpg') ||
      previewImage.toLowerCase().endsWith('.jpeg') ||
      previewImage.toLowerCase().endsWith('.gif') ||
      file.type.startsWith('image/');
    this.setState({
      previewImage,
      previewVisible,
    });
  };

  handleUploadOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      fileList: [],
      defaultFileList: null,
    });
  };

  handleUploadOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              value: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || { type: '' };
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const uploadProps = {
      // name: 'file',
      // action: '//jsonplaceholder.typicode.com/posts/',
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'config', isImage: false },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      defaultFileList: this.state.defaultFileList,
      multiple: false,
      accept:
        '.jpg, .jpeg, .png, .bmp, ' + //image/*
        '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,' + //excel
        '.doc,.docx,,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, ' + //word
        '.pdf, .txt, .xml',
    };
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    const inputCodeRules =
      type !== 'update'
        ? [
            {
              required: true,
              message: '参数编码必填',
            },
            {
              min: 0,
              max: 60,
              message: '最长60个字符',
            },
            rulesReg('letter_num__'),
            rulesRemote('POST', getWebPath('/sys/config/checkCfgCode'), {}),
          ]
        : [];
    //参数值：文本框
    const configValueNormal = (
      <FormItem label="参数值" {...formItemLayout}>
        {type === 'view'
          ? model.value
          : getFieldDecorator('value', {
              initialValue: model.value,
              rules: [
                {
                  required: true,
                  message: '参数值必填',
                },
                {
                  min: 0,
                  max: 400,
                  message: '参数值长度不在范围内',
                },
              ],
            })(<TextArea rows={3} maxLength={400} placeholder="参数值，根据具体参数进行取值" />)}
      </FormItem>
    );
    //参数值：上传图片
    const configValueUploadImg = (
      <FormItem label="图片" {...formItemLayout}>
        {type === 'view'
          ? model.value
          : getFieldDecorator('value', {
              initialValue: model.value,
              rules: [
                {
                  required: true,
                  message: '参数值必填',
                },
              ],
            })(
              <div className="clearfix">
                <Upload
                  {...uploadProps}
                  listType="picture-card"
                  onPreview={this.handleUploadPreview}
                >
                  {this.state.fileList && this.state.fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <Modal
                  visible={this.state.previewVisible}
                  footer={null}
                  onCancel={() => this.setState({ previewVisible: false })}
                >
                  <img alt="imgExample" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
              </div>
              // 文件类型
              // (
              //   <Upload
              //     {...uploadProps}
              //   >
              //     <Button>
              //       <Icon type="upload"/> 点击上传
              //     </Button>
              //   </Upload>
              // )
            )}
      </FormItem>
    );

    return (
      <Form layout="horizontal">
        <FormItem label="参数名" {...formItemLayout}>
          {type === 'view'
            ? model.keyAlias
            : getFieldDecorator('key', {
                initialValue: model.keyAlias,
                rules: [
                  {
                    required: true,
                    message: '参数名必填',
                  },
                  {
                    min: 0,
                    max: 30,
                    message: '长度不在范围内',
                  },
                ],
              })(<Input type="text" maxLength={30} placeholder="参数名,参数中文名称" />)}
        </FormItem>
        {this.state.configType === '6' || this.state.configType === '7'
          ? configValueUploadImg
          : configValueNormal}
        <FormItem label="参数类型" {...formItemLayout}>
          {type === 'view'
            ? getSysConfigTypeMap[model.type]
            : getFieldDecorator('type', {
                initialValue: model.type,
                rules: [
                  {
                    required: true,
                    message: '参数类型必填',
                  },
                ],
              })(
                <Select
                  onChange={value => {
                    this.setState({
                      configType: value,
                    });
                  }}
                >
                  <Option value="">请选项</Option>
                  {uiUtils.getOptionList(uiUtils.getOptionJsonObjToArr(getSysConfigTypeMap))}
                </Select>
              )}
        </FormItem>
        <FormItem label="参数编码" {...formItemLayout}>
          {type === 'view'
            ? model.code
            : getFieldDecorator('code', {
                initialValue: model.code,
                rules: inputCodeRules,
              })(
                <Input
                  type="text"
                  {...inputCodeDisabled}
                  maxLength={60}
                  autocomplete="off"
                  placeholder="参数值，根据具体参数进行取值"
                />
              )}
        </FormItem>
        <FormItem label="备注" {...formItemLayout}>
          {type === 'view'
            ? model.remark
            : getFieldDecorator('remark', {
                initialValue: model.remark,
                rules: [
                  {
                    min: 0,
                    max: 100,
                    message: '最长100个字符',
                  },
                ],
              })(<TextArea rows={3} maxLength={100} placeholder="备注" />)}
        </FormItem>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
